package com.java110.mall.shop.cmd.shop;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.CmdContextUtils;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.AuthenticationFactory;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.account.AccountBondObjDto;
import com.java110.dto.distributionMode.DistributionModeDto;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.store.StoreDto;
import com.java110.intf.acct.IAccountBondObjInnerServiceSMO;
import com.java110.intf.acct.IAccountInnerServiceSMO;
import com.java110.intf.goods.IDistributionModeInnerServiceSMO;
import com.java110.intf.shop.IShopInnerServiceSMO;
import com.java110.intf.user.*;
import com.java110.po.account.AccountBondObjPo;
import com.java110.po.distributionMode.DistributionModePo;
import com.java110.po.org.OrgPo;
import com.java110.po.org.OrgStaffRelPo;
import com.java110.po.privilege.PrivilegeUserPo;
import com.java110.po.shop.ShopPo;
import com.java110.po.store.StorePo;
import com.java110.po.user.StoreStaffPo;
import com.java110.po.user.UserPo;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.constant.StoreUserRelConstant;
import com.java110.utils.constant.UserLevelConstant;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 运营添加商户和商铺
 */
@Java110Cmd(serviceCode = "shop.adminAddStoreAndShop")
public class AdminAddStoreAndShopCmd extends Cmd {

    public static final String CODE_PREFIX_ID = "10";

    @Autowired
    private IStoreV1InnerServiceSMO storeV1InnerServiceSMOImpl;

    @Autowired
    private IStoreAttrV1InnerServiceSMO storeAttrV1InnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;

    @Autowired
    private IStoreStaffV1InnerServiceSMO storeUserV1InnerServiceSMOImpl;

    @Autowired
    private IOrgV1InnerServiceSMO orgV1InnerServiceSMOImpl;

    @Autowired
    private IOrgStaffRelV1InnerServiceSMO orgStaffRelV1InnerServiceSMOImpl;

    @Autowired
    private IPrivilegeUserV1InnerServiceSMO privilegeUserV1InnerServiceSMOImpl;

    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;

    @Autowired
    private IAccountInnerServiceSMO accountInnerServiceSMOImpl;

    @Autowired
    private IAccountBondObjInnerServiceSMO accountBondObjInnerServiceSMOImpl;


    @Autowired
    private IDistributionModeInnerServiceSMO distributionModeInnerServiceSMOImpl;


    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        Assert.hasKeyAndValue(reqJson, "address", "未包含店铺地址");
        Assert.hasKeyAndValue(reqJson, "areaAddress", "未包含区域地址");
        Assert.hasKeyAndValue(reqJson, "areaCode", "未包含区域");
        Assert.hasKeyAndValue(reqJson, "name", "未包含公司名称");
        Assert.hasKeyAndValue(reqJson, "nearbyLandmarks", "未包含附近");
        Assert.hasKeyAndValue(reqJson, "shopName", "未包含店铺名称");
        Assert.hasKeyAndValue(reqJson, "shopType", "未包含店铺类型");
        Assert.hasKeyAndValue(reqJson, "storeTypeCd", "未包含商户类型");
        Assert.hasKeyAndValue(reqJson, "tel", "未包含联系电话");
    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        String userId = CmdContextUtils.getUserId(cmdDataFlowContext);

        StoreDto storeDto = new StoreDto();
        storeDto.setTel(reqJson.getString("tel"));
        List<StoreDto> storeDtos = storeV1InnerServiceSMOImpl.queryStores(storeDto);

        if (storeDtos != null && storeDtos.size() > 0) {
            throw new IllegalArgumentException(reqJson.getString("tel") + "，手机号已经被占用 请更换或者联系管理员");
        }

        StorePo storePo = BeanConvertUtil.covertBean(reqJson, StorePo.class);
        storePo.setStoreId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        storePo.setStoreTypeCd(reqJson.getString("storeTypeCd"));
        storePo.setState(StoreDto.STATE_NORMAL);
        storePo.setName(reqJson.getString("name"));
        storePo.setCreateUserId(userId);
//        storePo.setUserId("-1");
        storePo.setAddress(reqJson.getString("address"));
        storePo.setTel(reqJson.getString("tel"));
//        storePo.setNearbyLandmarks(reqJson.getString("nearbyLandmarks"));
//        if (!reqJson.containsKey("mapY")) {
//            storePo.setMapY("1");
//        }
//        if (!reqJson.containsKey("mapX")) {
//            storePo.setMapX("1");
//        }
        int flag = storeV1InnerServiceSMOImpl.saveStore(storePo);

        if (flag < 1) {
            throw new CmdException("保存数据失败");
        }

        //添加用户
        UserPo userPo = new UserPo();
        userPo.setTel(reqJson.getString("tel"));
        userPo.setName(reqJson.getString("shopName"));
        userPo.setAddress(reqJson.getString("address"));
        userPo.setUserId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_userId));
        userPo.setScore("0");
        userPo.setAge("1");
        userPo.setEmail("无");
        userPo.setLevelCd(UserLevelConstant.USER_LEVEL_ADMIN);
        userPo.setSex("1");
        userPo.setPassword(AuthenticationFactory.passwdMd5(reqJson.getString("tel")));
        userPo.setbId("-1");
        flag = userV1InnerServiceSMOImpl.saveUser(userPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }

        //保存 商户和用户的关系
        StoreStaffPo storeUserPo = new StoreStaffPo();
        storeUserPo.setStoreStaffId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        storeUserPo.setAdminFlag(StoreUserRelConstant.REL_ADMIN);
        storeUserPo.setStoreId(storePo.getStoreId());
        storeUserPo.setStaffId(userPo.getUserId());
        storeUserPo.setStaffName(userPo.getName());
        storeUserPo.setTel(userPo.getTel());
        flag = storeUserV1InnerServiceSMOImpl.saveStoreStaff(storeUserPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }

        //保存公司级组织
        //保存公司级组织
        OrgPo orgPo = new OrgPo();
        orgPo.setOrgName(storePo.getName());
        orgPo.setOrgLevel("1");
        orgPo.setOrgId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_orgId));
        orgPo.setAllowOperation("F");
        orgPo.setBelongCommunityId("9999");
        orgPo.setParentOrgId(orgPo.getOrgId());
        orgPo.setStoreId(storePo.getStoreId());

        flag = orgV1InnerServiceSMOImpl.saveOrg(orgPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }

        //添加组织 员工关系
        OrgStaffRelPo orgStaffRelPo = new OrgStaffRelPo();
        orgStaffRelPo.setOrgId(orgPo.getOrgId());
        orgStaffRelPo.setStaffId(userPo.getUserId());
        orgStaffRelPo.setRelId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        orgStaffRelPo.setRelCd(StoreUserRelConstant.REL_ADMIN);
        orgStaffRelPo.setStoreId(storePo.getStoreId());
        flag = orgStaffRelV1InnerServiceSMOImpl.saveOrgStaffRel(orgStaffRelPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }


        String defaultPrivilege = MappingCache.getValue(MappingConstant.DOMAIN_DEFAULT_PRIVILEGE_ADMIN, StoreDto.STORE_TYPE_MALL);

        Assert.hasLength(defaultPrivilege, "未配置商城默认权限");
        PrivilegeUserPo privilegeUserPo = new PrivilegeUserPo();
        privilegeUserPo.setPrivilegeFlag("1");
        privilegeUserPo.setStoreId(storePo.getStoreId());
        privilegeUserPo.setUserId(userPo.getUserId());
        privilegeUserPo.setpId(defaultPrivilege);
        privilegeUserPo.setPuId(GenerateCodeFactory.getGeneratorId("10"));

        flag = privilegeUserV1InnerServiceSMOImpl.savePrivilegeUser(privilegeUserPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }

        //保存商铺
        saveShop(storePo, reqJson);

    }




    private void saveShop(StorePo storePo, JSONObject reqJson) {
        ShopPo shopPo = new ShopPo();
        shopPo.setShopName(reqJson.getString("shopName"));
        shopPo.setShopDesc("店铺比较懒未完善店铺信息");
        shopPo.setReturnPerson(reqJson.getString("shopName"));
        shopPo.setReturnLink(reqJson.getString("tel"));
        shopPo.setStoreId(storePo.getStoreId());
        shopPo.setSendAddress(reqJson.getString("areaAddress") + reqJson.getString("address"));
        shopPo.setReturnAddress(reqJson.getString("areaAddress") + reqJson.getString("address"));
        shopPo.setShopType(reqJson.getString("shopType"));
        shopPo.setOpenType(ShopDto.OPEN_TYPE_SHOP);
        shopPo.setShopRange("无");
        shopPo.setAreaCode(reqJson.getString("areaCode"));
        shopPo.setShopId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_shopId));
        shopPo.setShopLogo("");
        shopPo.setMapX("1");
        shopPo.setMapY("1");

        shopPo.setState(ShopDto.STATE_Y);
        //shopPo.setState(ShopDto.STATE_B);

        int flag = shopInnerServiceSMOImpl.saveShop(shopPo);
        if (flag < 1) {
            throw new CmdException("保存商铺失败");
        }

        //默认保存保证金应收信息
        //saveAccountBond(accoutBond, shopPo);

        //添加派送方式
        DistributionModePo distributionModePo = new DistributionModePo();
        distributionModePo.setFixedFee("0");
        distributionModePo.setbId("-1");
        distributionModePo.setMaximumDistribution("-1");
        //处理商品与配送方式关系
        distributionModePo.setModeId(GenerateCodeFactory.getGeneratorId("16"));
        distributionModePo.setShopId(shopPo.getShopId());
        distributionModePo.setModeName("到店自提");
        distributionModePo.setModeType(DistributionModeDto.MODE_TYPE_USER);
        distributionModePo.setStartDeliveryIn("-1");
        distributionModePo.setStartDeliveryOut("-1");
        flag = distributionModeInnerServiceSMOImpl.saveDistributionMode(distributionModePo);
        if (flag < 1) {
            throw new CmdException("保存店铺配送方式失败");
        }

        reqJson.put("shopId", shopPo.getShopId());

    }

    private void saveAccountBond(JSONObject accoutBond, ShopPo shopPo) {

        AccountBondObjPo accountBondObjPo = new AccountBondObjPo();
        accountBondObjPo.setBobjId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_bobjId));
        accountBondObjPo.setBondId(accoutBond.getString("bondId"));
        accountBondObjPo.setObjId(shopPo.getShopId());
        accountBondObjPo.setObjName(shopPo.getShopName());
        accountBondObjPo.setBondType(accoutBond.getString("bondType"));
        accountBondObjPo.setState("1001");
        if (ShopDto.STATE_F.equals(shopPo.getState())) {
            accountBondObjPo.setState(AccountBondObjDto.STATE_BUY_FINISH);
        }
        accountBondObjPo.setReceivableAmount(accoutBond.getString("amount"));

        accountBondObjPo.setStartTime(DateUtil.getNow("yyyy-MM-dd"));
        Calendar curr = Calendar.getInstance();
        curr.set(Calendar.MONTH, curr.get(Calendar.MONTH) + Integer.parseInt(accoutBond.getString("bondMonth")));
        Date date = curr.getTime();
        accountBondObjPo.setEndTime(DateUtil.getFormatTimeString(date, "yyyy-MM-dd"));
        accountBondObjPo.setReceivedAmount("0");
        accountBondObjPo.setRemark("系统自动生成保证金对象信息:" + accoutBond.getString("remark"));

        int flag = accountBondObjInnerServiceSMOImpl.saveAccountBondObj(accountBondObjPo);
        if (flag < 0) {
            throw new IllegalArgumentException("保存保证金对象失败");
        }

    }
}
